import tkinter as tk
from tkinter import scrolledtext, messagebox, ttk
import re


def process_bibitems():
    input_text = input_area.get("1.0", tk.END)
    if not input_text.strip():
        messagebox.showwarning("警告", "请输入要处理的BibItem文本！")
        return

    # 使用正则表达式找到每个bibitem块
    pattern = r'(\\bibitem\{[^}]*\})([\s\S]*?)(?=\\bibitem|\Z)'

    def replace_func(match):
        bibitem_cmd = match.group(1)  # \bibitem{...}
        content = match.group(2).lstrip()

        # 查找第一个句号位置
        dot_pos = content.find('.')
        if dot_pos != -1:
            author_part = content[:dot_pos]  # 作者名部分
            rest_of_content = content[dot_pos:]  # 句号及之后内容

            # 检查是否已包含"et al"
            if "et al" in author_part.lower():
                # 保留现有的"et al"，但将前面的内容转为大写
                et_al_pos = author_part.lower().find("et al")
                names_before_et_al = author_part[:et_al_pos].upper()
                et_al_and_after = author_part[et_al_pos:]  # 保持"et al"原样
                processed_authors = names_before_et_al + et_al_and_after
            else:
                # 按逗号分割作者名
                author_segments = [seg.strip() for seg in author_part.split(',')]

                # 如果作者超过三个，只保留前三个并添加"et al"
                if len(author_segments) > 3:
                    first_three_authors = author_segments[:3]
                    processed_authors = ', '.join(first_three_authors).upper() + ', et al'
                else:
                    # 将所有作者名转为大写
                    processed_authors = author_part.upper()

            processed_content = processed_authors + rest_of_content
        else:
            processed_content = content

        return bibitem_cmd + '\n\t' + processed_content

    processed_text = re.sub(pattern, replace_func, input_text)

    # 将处理后的文本显示在输出区域
    output_area.delete("1.0", tk.END)
    output_area.insert("1.0", processed_text)

    # 更新状态栏
    status_var.set("处理完成！")


def clear_text():
    input_area.delete("1.0", tk.END)
    output_area.delete("1.0", tk.END)
    status_var.set("已清空")


def copy_to_clipboard():
    try:
        output_text = output_area.get("1.0", tk.END)
        if not output_text.strip():
            messagebox.showwarning("警告", "没有可复制的内容！")
            return

        root.clipboard_clear()
        root.clipboard_append(output_text)
        status_var.set("已复制到剪贴板")
        messagebox.showinfo("复制成功", "文本已复制到剪贴板")
    except Exception as e:
        messagebox.showerror("复制失败", str(e))


def load_example():
    example_text = """\bibitem{chakrabarty2018statistical}
	Chakrabarty N, Biswas S. A statistical approach to adult census income level prediction[C]. 2018 International Conference on Advances in Computing, Communication Control and Networking (ICACCCN), 2018: 207--212.

\bibitem{subasi2019prediction}
	Subasi A, Cankurt S. Prediction of default payment of credit card clients using Data Mining Techniques[C]. 2019 International engineering conference (IEC), 2019: 115--120.

\bibitem{smith2022example}
	Smith J et al. Some example paper with multiple authors[J]. Journal of Examples, 2022: 45-50.

\bibitem{liu2021fate}
	Liu Y, Fan T, Chen T, Xu Q, Yang Q. Fate: An industrial grade platform for collaborative learning with data protection[J]. Journal of Machine Learning Research, 2021, 22(156): 1-6."""

    input_area.delete("1.0", tk.END)
    input_area.insert("1.0", example_text)
    status_var.set("已加载示例")


# 创建主窗口
root = tk.Tk()
root.title("BibItem 作者名转换工具")
root.geometry("850x650")
root.configure(bg="#f5f5f5")

# 设置样式
style = ttk.Style()
style.configure("TButton", font=("Arial", 10), padding=5)
style.configure("TLabel", font=("Arial", 10), background="#f5f5f5")
style.configure("TLabelframe", background="#f5f5f5")
style.configure("TLabelframe.Label", font=("Arial", 10, "bold"), background="#f5f5f5")
style.configure("Header.TLabel", font=("Arial", 16, "bold"), background="#f5f5f5")
style.configure("Status.TLabel", background="#e1e1e1", padding=3)

# 创建主框架
main_frame = ttk.Frame(root, padding="10", style="TLabelframe")
main_frame.pack(fill=tk.BOTH, expand=True)

# 创建标题
title_label = ttk.Label(main_frame, text="BibItem 作者名转换工具", style="Header.TLabel")
title_label.pack(pady=10)

# 创建说明
instruction_frame = ttk.Frame(main_frame)
instruction_frame.pack(fill=tk.X, pady=5)

instruction_text = """功能说明:
1. 将BibItem条目中第一个句号前的作者名转换为大写
2. 保留'et al.'的小写形式
3. 如果作者数量超过三个，则仅保留前三位作者，其余替换为'et al'"""

instruction_label = ttk.Label(instruction_frame, text=instruction_text, wraplength=600, justify="left")
instruction_label.pack(side=tk.LEFT, pady=5)

example_button = ttk.Button(instruction_frame, text="加载示例", command=load_example)
example_button.pack(side=tk.RIGHT, padx=5)

# 创建示例
example_frame = ttk.Frame(main_frame)
example_frame.pack(fill=tk.X, pady=2)

example_text1 = "示例1: Chakrabarty N, Biswas S → CHAKRABARTY N, BISWAS S"
example_label1 = ttk.Label(example_frame, text=example_text1, font=("Arial", 9, "italic"))
example_label1.pack(anchor=tk.W)

example_text2 = "示例2: Smith J et al. → SMITH J et al."
example_label2 = ttk.Label(example_frame, text=example_text2, font=("Arial", 9, "italic"))
example_label2.pack(anchor=tk.W)

example_text3 = "示例3: Liu Y, Fan T, Chen T, Xu Q, Yang Q → LIU Y, FAN T, CHEN T, et al"
example_label3 = ttk.Label(example_frame, text=example_text3, font=("Arial", 9, "italic"))
example_label3.pack(anchor=tk.W)

# 创建水平分割线
separator = ttk.Separator(main_frame, orient='horizontal')
separator.pack(fill=tk.X, pady=10)

# 创建输入区域
input_frame = ttk.LabelFrame(main_frame, text="输入 BibItem 文本")
input_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

input_area = scrolledtext.ScrolledText(input_frame, wrap=tk.WORD, font=("Consolas", 10), bg="#ffffff")
input_area.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

# 创建按钮区域
button_frame = ttk.Frame(main_frame)
button_frame.pack(fill=tk.X, padx=5, pady=5)

process_button = ttk.Button(button_frame, text="📝 处理文本", command=process_bibitems, width=15)
process_button.pack(side=tk.LEFT, padx=5)

clear_button = ttk.Button(button_frame, text="🗑️ 清空", command=clear_text, width=10)
clear_button.pack(side=tk.LEFT, padx=5)

# 创建输出区域
output_frame = ttk.LabelFrame(main_frame, text="处理后的文本")
output_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

output_area = scrolledtext.ScrolledText(output_frame, wrap=tk.WORD, font=("Consolas", 10), bg="#f0f8ff")
output_area.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

# 创建复制按钮
copy_button = ttk.Button(main_frame, text="📋 复制到剪贴板", command=copy_to_clipboard, width=20)
copy_button.pack(pady=10)

# 创建状态栏
status_var = tk.StringVar()
status_var.set("就绪")
status_bar = ttk.Label(root, textvariable=status_var, relief=tk.SUNKEN, anchor=tk.W, style="Status.TLabel")
status_bar.pack(side=tk.BOTTOM, fill=tk.X)

# 启动主循环
root.mainloop()